package com.gree.portal.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.gree.commom.result.BaseResult;
import com.gree.portal.service.CookinService;
import com.gree.portal.service.UserService;
import com.gree.rpc.service.SendMessageService;
import com.gree.sso.entity.Admin;
import com.gree.sso.service.SSOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Reference(interfaceClass = SSOService.class)
    private SSOService ssoService;

    @Reference(interfaceClass = SendMessageService.class)
    private SendMessageService sendMessageService;

    @Autowired
    private CookinService cookinService;

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param admin
     * @param request
     * @param response
     * @return
     * @throws JsonProcessingException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("/login")
    @ResponseBody
    private BaseResult login(Admin admin, HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException, NoSuchAlgorithmException {
        //登录成功并生成票据
        String ticket = ssoService.login(admin);
        if(!StringUtils.isEmpty(ticket)){
            boolean result = cookinService.setCookie(request, response, ticket);
            request.getSession().setAttribute("user",admin);
            return result == true?BaseResult.success():BaseResult.error();
        }
        return BaseResult.error();
    }

    /**
     * 用户退出
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        //清除redis
        String ticket = cookinService.getCookie(request);
        ssoService.logout(ticket);
        //清除session
        request.getSession().removeAttribute("user");
        //清除cookie
        cookinService.deleteCookie(request,response);
        return "login";
    }

    /**
     * 用户注册
     */
    @RequestMapping("/register")
    @ResponseBody
    public BaseResult register(Admin admin) throws Exception {
        BaseResult baseResult = userService.saveUser(admin);
        if (baseResult.getCode() == 200){
            //发送短信通知用户
            BaseResult result = sendMessageService.sendMessage(admin.getEmail());
            if (result.getCode() == 200){
                return BaseResult.success();
            }
        }
        return BaseResult.error();
    }
}
